package com.effects;

import com.Utils;
import static com.effects.BasicEffect.rainbow;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;

/**
 * @author sad
 */
public class AmplitudeEffect extends BasicEffect {

    @Override
    public String getEffectName() {
        return "Amplitude";
    }

    @Override
    public String getId() {
        return "ampl";
    }

    private final double[] tArray = new double[78];

    private double[] getAmplitude(byte[] pcm) {
        int factor = pcm.length / (78 * 2);
        int sample = 0;
        double min = 9999999999d;
        double max = 0;
        for (int j = 0; j < 78; j++) {
            tArray[j] = 0;
            for (int i = 0; i < factor; i++, sample += 2) {
                int value = Utils.lhTo16Bit(pcm[sample], pcm[sample+1]);
                tArray[j] += value;
            }
            if (min > tArray[j]) {
                min = tArray[j];
            }
            if (max < tArray[j]) {
                max = tArray[j];
            }
        }

        max -= min;
        for (int i = 0; i < tArray.length; i++) {
            double value = tArray[i];
            value -= min;
            value = value / max;
            tArray[i] = value;
        }
        return tArray;
    }

    
    int offset=0;
    @Override
    public BufferedImage getImage(byte[] pcm) {
        //double[] tSpectrum = spectrum(pcm);
        //if (tSpectrum == null) {
        //    return null;
        //}
        double[] amplitude = spectrum(pcm);
        alphaClearingImage(image, 40);
        Graphics g = image.getGraphics();
        //g.setColor(Color.BLACK);
        //g.fillRect(0, 0, image.getWidth(), image.getHeight());
        g.setColor(Color.green);
        int height = image.getHeight();
        for (int i = 0; i < amplitude.length; i++) {
            g.setColor(getRainbow(i, offset));
            int size = (int) (amplitude[i] * 40);
            g.drawLine(i, height / 2 - size / 2, i, height / 2 + size / 2);
        }
        offset+=1;
        return image;
    }

}
